package jlxy.ise.eroad.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.util.TextUtils;
import jlxy.ise.eroad.R;
import jlxy.ise.eroad.activity.LoginActivity;
import jlxy.ise.eroad.activity.MyInfoActivity;
import jlxy.ise.eroad.base.BaseSwitchFragment;
import jlxy.ise.eroad.bean.ServerRpsInfo;
import jlxy.ise.eroad.util.C;
import jlxy.ise.eroad.util.SingleToast;
import jlxy.ise.eroad.util.WebUtil;


/**
 * 我的页面
 *
 * @author chen
 */
public class MyFragment extends BaseSwitchFragment implements OnClickListener {

    private static final String TAG = MyFragment.class.getSimpleName();

    private View rootView;
    private TextView mTxUserName;

    private LinearLayout mLyPerson;
    private LinearLayout mLyPwd;
    private LinearLayout mLyAbout;
    private LinearLayout mLyExit;

    private TextView mTxMyStatus;
    private static MyFragment instance;

    public MyFragment() {
    }

    public static MyFragment getInstance() {
        if (instance == null) instance = new MyFragment();
        return instance;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_my, container, false);

        mTxUserName = (TextView) rootView.findViewById(R.id.tx_username);
        mTxMyStatus = (TextView) rootView.findViewById(R.id.tx_status_change);

        mLyPerson = (LinearLayout) rootView.findViewById(R.id.ly_person);
        mLyPwd = (LinearLayout) rootView.findViewById(R.id.ly_pwd);
        mLyAbout = (LinearLayout) rootView.findViewById(R.id.ly_about);
        mLyExit = (LinearLayout) rootView.findViewById(R.id.ly_exit);

        mLyPerson.setOnClickListener(this);
        mLyPwd.setOnClickListener(this);
        mLyAbout.setOnClickListener(this);
        mLyExit.setOnClickListener(this);
        mTxMyStatus.setOnClickListener(this);


        //填充个人信息
        mTxUserName.setText(mAct.getString(
                R.string.driver_s_id_name_tel, getDriverInfo().getId() + "",
                TextUtils.isEmpty(getDriverInfo().getName()) ? "暂无" : getDriverInfo().getName(), getDriverInfo().getTelephone()));
        return rootView;
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tx_status_change:
                //查询车辆状态
                showStateDialog();
                break;
            case R.id.ly_person:
                Intent itPerson = new Intent(mAct, MyInfoActivity.class);
                itPerson.putExtra(C.INTENT_TYPE.DATA_OBJ, getString(R.string.setting_modify_personal));
                mAct.startActivity(itPerson);
                break;
            case R.id.ly_pwd:
                Intent itPwd = new Intent(mAct, MyInfoActivity.class);
                itPwd.putExtra(C.INTENT_TYPE.DATA_OBJ, getString(R.string.setting_modify_pwd));
                mAct.startActivity(itPwd);
                break;
            case R.id.ly_about:
                Intent intent = new Intent(mAct, MyInfoActivity.class);
                intent.putExtra(C.INTENT_TYPE.DATA_OBJ, getString(R.string.setting_about_app));
                mAct.startActivity(intent);
                break;
            case R.id.ly_exit:
                showExitDialog();
                break;
            default:
                break;
        }
    }

    public static boolean isRefresh = false;

    @Override
    public void onResume() {
        super.onResume();

        if (isRefresh) {
            isRefresh = false;
            //填充个人信息
            mTxUserName.setText(mAct.getString(
                    R.string.driver_s_id_name_tel, getDriverInfo().getId() + "",
                    TextUtils.isEmpty(getDriverInfo().getName()) ? "暂无" : getDriverInfo().getName(), getDriverInfo().getTelephone()));
        }

    }

    private void showExitDialog() {
        new MaterialDialog.Builder(mAct)
                .content(R.string.loginout_info)
                .positiveText(android.R.string.ok).onPositive(new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(MaterialDialog dialog, DialogAction which) {
                logout();
            }
        }).negativeText(android.R.string.cancel).show();
    }


    private String getState(int state) {
        //0：空闲 1：竞价 2：运输 3：休整
        switch (state) {
            case 0:
                return "空闲";
            case 1:
                return "竞价";
            case 2:
                return "运输";
            case 3:
                return "休整";
            default:
                return "空闲";
        }
    }

    /**
     * 展示运输状态的对话框
     */
    private void showStateDialog() {

        new MaterialDialog.Builder(mAct)
                .title("查看当前汽车状态")
                .content("当前状态为：" + getState(getDriverInfo().getState()))
                .positiveText("改为运输")
                .negativeText("改为休整")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        changeState(2);
                    }
                })
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        dialog.dismiss();
                        changeState(3);
                    }
                })
                .show();
    }

    private void changeState(final int state) {
        //修改状态
        WebUtil.postStateAlter(WebUtil.getRpStateAlter(mApp.getDriverInfo().getId() + "", state + ""), new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Gson gson = new Gson();
                try {
                    ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                    if (serverRpsInfo.getStatus().equals("ok") && serverRpsInfo.getMessage().equals("ok")) {
                        SingleToast.showToast(mAct, "修改汽车状态成功", 2000);
                        getDriverInfo().setState(state);
                    }
                } catch (Exception e) {
                    SingleToast.showToast(mAct, "修改汽车状态出错:" + e.getLocalizedMessage(), 2000);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                SingleToast.showToast(mAct, "修改汽车状态失败", 2000);
            }
        });
    }


    /**
     * 登出
     */
    private void logout() {
        mApp.cleanCache();

        //修改登录状态为上线
        Date date = new Date();
        SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        String currentTime = time.format(date);
        WebUtil.postExitAlter(WebUtil.getRpExitAlter(getDriverInfo().getId() + "", "0"), new JsonHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Gson gson = new Gson();
                try {
                    ServerRpsInfo serverRpsInfo = gson.fromJson(response.toString(), ServerRpsInfo.class);
                    if (serverRpsInfo.getStatus().equals("ok") && serverRpsInfo.getMessage().equals("ok")) {
//						SingleToast.showToast(getApplicationContext(), "用户已下线", 2000);
                    }
                } catch (Exception e) {
                    //SingleToast.showToast(getApplicationContext(), "修改用户状态出错:" + e.getLocalizedMessage(), 2000);
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
                super.onFailure(statusCode, headers, throwable, errorResponse);
                //SingleToast.showToast(getApplicationContext(), "修改用户状态失败", 2000);
            }
        });

        Intent loginIntent = new Intent(mAct, LoginActivity.class);
        loginIntent.putExtra("type", "loginout");
        startActivity(loginIntent);
        mAct.finish();
        mAct.overridePendingTransition(R.anim.slide_in_bottom,
                R.anim.slide_out_top);
    }


}
